from flask import Flask,url_for,render_template,request,jsonify,make_response
import requests
import json
import re
from lxml import etree
app=Flask(__name__)

@app.route("/",methods=["GET"])
def index():
    return render_template("index.html")

@app.route("/search",methods=["GET"])
def search():
    key=request.args["key"]
    page = request.args.get("page",default=1)
    url="http://api.ali.17k.com/v2/book/search?app_key=2222420362&key={}&page={}&book_free=&finish=&class=".format(key,page)
    res=requests.get(url)
    res=res.content.decode()
    res=json.loads(res)
    res['data'].pop(0)
    has_next = False
    if res['total_page']>page:
        has_next=True
    response=make_response()
    return render_template("search.html",items=res['data'],has_next=has_next,total_num=res["total_num"])

@app.route("/api/search",methods=["GET"])
def search_api():
    key=request.args["key"]
    page = request.args.get("page",default=1)
    url="http://api.ali.17k.com/v2/book/search?app_key=2222420362&key={}&page={}&book_free=&finish=&class=".format(key,page)
    res=requests.get(url)
    res=res.content.decode()
    res=json.loads(res)
    return jsonify(res)

@app.route("/detail/<int:id>",methods=["GET"])
def detail(id):
    url = "http://www.17k.com/book/{}.js".format(id)
    res = requests.get(url)
    res = res.content.decode()
    res = re.match(r"Q.bookBigData.load\((.*)\)",res).group(1)
    res = json.loads(res)
    return render_template("detail.html",item=res)

@app.route("/api/catalog/<int:book_id>",methods=["POST"])
def catalog_api(book_id):
    page=request.form.get("page",default="1")
    num=request.form.get("num",default="20")
    order=request.form.get("order",default="asc")
    url = "http://api.17k.com/v2/book/{}/volumes/limit?app_key=2222420362&order_by={}&num={}&page={}".format(book_id,order,num,page)
    res = requests.get(url)
    res = res.content.decode()
    res=json.loads(res)
    return jsonify(res)

@app.route("/catalog/<int:book_id>",methods=["GET"])
def catalog(book_id):
    catalog_id=request.args.get("catalog_id",default="0")
    page=request.args.get("page",default="1")
    return render_template("catalog.html",book_id=book_id,catalog_id=catalog_id,page=page)

@app.route("/catalog_detail/<int:book_id>/<int:catalog_id>",methods=["GET"])
def catalog_detail(book_id,catalog_id):
    url="http://h5.17k.com/chapter/{}/{}.html".format(book_id,catalog_id)
    page = request.args.get("page", default="1")
    res = requests.get(url)
    res = res.content.decode()
    title=re.findall(r"<title>(.*)</title>",res)[0]
    h1=re.findall(r"<h1>(.*)</h1>",res)[0]
    article=re.findall(r"<article>(.*)</article>",res,flags=re.DOTALL)[0]
    return render_template("catalog_detail.html",title=title,h1=h1,article=article,book_id=book_id,catalog_id=catalog_id,page=page)

@app.route("/api/like",methods=["GET"])
def like_api():
    url="http://api.ali.17k.com/v2/book/boutique/user/like/0?app_key=2222420362"
    res=requests.get(url)
    res=json.loads(res.content.decode())
    return jsonify(res)

@app.route("/categrey",methods=["GET"])
def categrey():
    boys=[]
    girls=[]
    mys=[]
    for i in range(2,5):
        url = "http://api.17k.com/v2/book/category/%d?app_key=1351550300" % i
        res = requests.get(url)
        res = json.loads(res.content.decode())
        if i==2:
            boys=res["data"]["child_node"]
        elif i==3:
            girls = res["data"]["child_node"]
        else:
            mys = res["data"]["child_node"]
    return render_template("categrey.html",boys=boys,girls=girls,mys=mys)

@app.route("/api/categrey/<int:cate_id>",methods=["GET"])
def categrey_api(cate_id):
    url="http://api.17k.com/v2/book/category/{}?app_key=1351550300".format(cate_id)
    res = requests.get(url)
    res = json.loads(res.content.decode())
    return jsonify(res)

@app.route("/categrey_detail/<int:site>/<int:cate1_id>/<int:cate2_id>",methods=["GET"])
def categrey_detail(site,cate1_id,cate2_id):
    url="http://api.17k.com/v2/book?app_key=1351550300&site={}&category_1={}&category_2={}&sort_type=1&book_free=2&book_status=1&page=1&num=10".format(site,cate1_id,cate2_id)
    res = requests.get(url)
    res = json.loads(res.content.decode())
    return  render_template("categrey_detail.html",res=res)

#排行榜
@app.route("/sort",methods=["GET"])
def sort_api():
    url="http://h5.17k.com/topv3.html"
    res = requests.get(url)
    res=res.content.decode()
    root=etree.HTML(res)
    items=[]
    label_list=root.xpath("//section[@class='TAB_title']//label")
    for label in label_list:
        item=[]
        href_list=root.xpath("//dl[contains(@class,'%s')]/dt/a/@href" % label.xpath("./@rel")[0])
        title_list = root.xpath("//dl[contains(@class,'%s')]/dt/a/span/text()" % label.xpath("./@rel")[0])
        i=0
        for title in title_list:
            item1={
                "title":title,
                "href":href_list[i]
            }
            i+=1
            item.append(item1)
        items.append(item)
    return  render_template("sort.html",items=items)

@app.route("/sort_detail",methods=["GET"])
def sort_detail():
    href=request.args.get("href")
    href="http://h5.17k.com"+href
    res=requests.get(href).content.decode()
    root=etree.HTML(res)
    li_list=root.xpath("//ul[@class='xinshubang']/li")
    items=[]
    title=root.xpath("//header/span/text()")[0]
    for li in li_list:
        item1 = {}
        item1["name"] = li.xpath(".//p[1]/text()")[0]
        item1["img"] = li.xpath(".//a/img/@data_src")[0]
        item1["intro"] = li.xpath(".//p[3]/text()")[0]
        item1["author"] = li.xpath(".//p[2]/text()")[0]
        item1["id"]=re.match(r"/book/(\d+).html",li.xpath(".//a/@href")[0]).group(1)
        items.append(item1)
    return render_template("sort_detail.html",items=items,title=title)

@app.route("/collect",methods=["GET"])
def collect():
    collects=request.cookies.get("collects",default="")
    collect_imgs=request.cookies.get("collect_imgs",default="")
    if collects=="":
        items=[]
    else:
        collect_imgs=collect_imgs.split(",")
        collects_list=collects.split(",")
        items=[]
        i=0
        print(collects_list,collect_imgs)
        for id in collects_list:
            url = "http://www.17k.com/book/{}.js".format(id)
            res = requests.get(url)
            res = res.content.decode()
            res = re.match(r"Q.bookBigData.load\((.*)\)", res).group(1)
            res = json.loads(res)
            res["img"]=collect_imgs[i]
            items.append(res)
            i+=1
    return  render_template("collect.html",items=items)

if __name__=="__main__":
    app.run(debug=True)
